package com.itheima.wms.service.impl;

import com.itheima.wms.mapper.GetCodeFactoryMapper;
import com.itheima.wms.pojo.Factory;
import com.itheima.wms.service.GetCodeFactoryService;
import com.itheima.wms.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
@Slf4j
@RequiredArgsConstructor
public class GetCodeFactoryServiceImpl implements GetCodeFactoryService {
    private final GetCodeFactoryMapper getCodeFactoryMapper;
    private final HttpServletRequest request;

    @Override
    public String getCodeFactory(String type) {
        Factory codeFactory = getCodeFactoryMapper.getCodeFactory(type);
        String jwt = request.getHeader("Authorization");
        Map<String, Object> map = JwtUtil.parseJwt(jwt);

        String name = (String)map.get("name");
        log.info(name);

        if(codeFactory == null){
            getCodeFactoryMapper.insertCodeFactory(new Factory(null,type,"1001",1,type,name,name, LocalDateTime.now(),LocalDateTime.now()));
            return type+"1001";
        }

        String returnType = codeFactory.getType();
        String content = codeFactory.getContent();
        String s = String.valueOf(Integer.parseInt(content) + 1);

        codeFactory.setContent(s);
        codeFactory.setUpdateName(name);
        codeFactory.setUpdateTime(LocalDateTime.now());
        getCodeFactoryMapper.update(codeFactory);
        return returnType+s;
    }

}
